package com.java2108.user.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.zhanggm.common.AjaxResult;
import com.java2108.user.entity.User;
import com.java2108.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping("/user/")
@RestController
public class LoginController {

    @Autowired
    IUserService iUserService;


    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {

        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return AjaxResult.error("用户名或密码错误");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User loginUser = iUserService.getOne(queryWrapper);

        if (loginUser == null) {
            return AjaxResult.error("用户名或密码错误");
        }

        /*JWT jwt = JWT.create().setPayload("username", loginUser.getUsername())
                .setPayload("id", loginUser.getId());*/
        loginUser.setPassword(null);
        String token = JWTUtil.createToken(BeanUtil.beanToMap(loginUser), "123456".getBytes());

        return AjaxResult.success(token);

    }


}

